// Client.java - Peer to Peer Client

import java.io.*;
import java.net.*;


/*
  Connects to Server
  Gets services from Server

*/

public class Client
{

  String SERVER_HOST = new String("localhost");
  int SERVER_PORT = 0;
  Socket serversSocket;

  BufferedReader mySocketReader,myInputReader;
  PrintWriter mySocketWriter;

  public Client(String arg)
  {
    try{

         SERVER_PORT = Integer.parseInt(arg);
         serversSocket = new Socket(InetAddress.getByName(SERVER_HOST), SERVER_PORT);
         mySocketReader = new BufferedReader(new InputStreamReader(serversSocket.getInputStream()));
         myInputReader = new BufferedReader(new InputStreamReader(System.in));
         mySocketWriter = new PrintWriter(new OutputStreamWriter(serversSocket.getOutputStream()));
    }catch( ConnectException ce){ System.out.println("Please start the server First at port # "+ SERVER_PORT); }
     catch( Exception e){ e.printStackTrace(); }  
  
  }//End constructor

  public void login() throws IOException
  { 
    //System.out.println("Enter your login name");
    //String loginName = new String(myInputReader.readLine());
    //mySocketWriter.println(loginName);
    mySocketWriter.println("Kunal login");
    mySocketWriter.flush(); 

  }// end login

  public void getServices()
  {
    try{

        boolean lastLine = false;
        while(!lastLine)
        {
           String temp = new String(mySocketReader.readLine());
            if(temp.equalsIgnoreCase("endFlag"))
            {
              lastLine = true;
            }else{
              System.out.println(temp);
            }
        }

       }catch(NullPointerException ne){ System.out.println("Server Disconnected");}
        catch(Exception e){ e.printStackTrace();}
  }//End getServices
  
  public void sendServiceRequest() throws IOException
  {
     
   System.out.println("Waiting for your input");
   String requestNumber = new String(myInputReader.readLine());
   mySocketWriter.println(requestNumber);
   mySocketWriter.flush();
   //return Integer.parseInt(requestNumber);
 
  }//End sendServiceRequest()


  public static void main(String args[])
  {
   Client c = null;
   try{

        if(args.length != 1)
        { 
          System.out.println("Enter Port Number of Server in Command Line\nUSAGE: java Client SERVER_PORT_NO");
          System.exit(0);   
        }else{
               c = new Client(args[0]);
               c.login();
               //c.getServices();
             }

      }catch(Exception e){ e.printStackTrace(); }

   while(true)
   {
     try{
          c.getServices();
          c.sendServiceRequest();    
          c.getServices();         
     }catch(Exception e){e.printStackTrace();}
   }//end while

  }//End main 
  

}//End Client
